/**send mail utils of huilin core frame work
 * by fuzhou huilin corp.ltd @author lms 2016.07.21
 */
package ms.core.tool;

import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailTool { 
	
	private static MimeMessage createMailContent(Session session, MailMsg mail){
		MimeMessage message = new MimeMessage(session);
		try{
			message.setFrom(new InternetAddress(mail.getSender()));
			List<String> recs = StrTool.splitString(mail.getReceiver(), ",");
			for (String rec: recs){
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(rec));
			}
			if (!StrTool.isBlank(mail.getCC())){
				List<String> ccs = StrTool.splitString(mail.getCC(), ",");
				for(String cc: ccs){
					message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
				}
			}

			//set subject
			message.setSubject(mail.getSubject());
			//set content
			MimeBodyPart text = new MimeBodyPart();
			text.setContent(mail.getMessage(),"text/html;charset=UTF-8");

			MimeMultipart multipart = new MimeMultipart();
			multipart.addBodyPart(text);
			//set attachments
			if (mail.getAnnexs()!=null && mail.getAnnexs().size()>0) {
				for(int i=0; i<mail.getAnnexs().size(); i++) {
					String annex = mail.getAnnexs().get(i);
					if (SysTool.fileExists(annex)==1){
						MimeBodyPart attach = new MimeBodyPart();
						DataHandler dh = new DataHandler(new FileDataSource(annex));
						attach.setDataHandler(dh);
						attach.setFileName(dh.getName());
						multipart.addBodyPart(attach);
					}
				}
			}
			multipart.setSubType("mixed");
			message.setContent(multipart);
			message.saveChanges();
			return message;
		}catch(Exception e){
			Log4j2Tool.error(MailTool.class, "createMailContent:", e);
			return null;
		}
	}
	
	/**
	 * 发送邮件接口
	 * @param mail
	 * @return
	 */
	public static boolean sendMail(final MailMsg mail){
		boolean ret=false;
		try{
			Properties props = new Properties();
			//set properties of mail server
			props.put("mail.smtp.host",mail.getHost());
			props.put("mail.smtp.port",mail.getPort());
			props.put("mail.smtp.connectiontimeout", mail.getConnectTimeout());
			props.put("mail.smtp.timeout", mail.getSendTimeout());
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.auth",mail.getAuth());
			if (mail.isTls()) {
				props.put("mail.smtp.starttls.enable", "true");
				props.put("mail.smtp.ssl.checkserveridentity", "false");
				props.put("mail.smtp.ssl.trust", mail.getHost());
			}
			
			//initialize session and transport
			Session session = Session.getDefaultInstance(props,null);
			session.setDebug(mail.isDebug());
			
			Transport ts = session.getTransport();
			ts.connect(mail.getHost(), mail.getSender(), mail.getPassword());
			//initialize mail sender,receiver,subject and content
			Message msg = createMailContent(session, mail);
			if (msg!=null){
				ts.sendMessage(msg, msg.getAllRecipients());
				ret = true;
			}
			ts.close();
			ts = null;
		}catch(Exception e){
			Log4j2Tool.error(MailTool.class, "sendMail:", e);
			ret = false;
		}
		return ret;
	}

	public static class MailMsg {
		public static final String ENCODEING = "UTF-8";
		private String host; 				// mail host
		private int port; 					// mail port
		private int connectTimeout; 		// mail connect timeout(ms)
		private int sendTimeout; 			// mail send timeout(ms)
		private boolean auth; 				// mail host need authorization
		private boolean debug; 				// 是否开启DEBUG
		private boolean tls; 				// 是否启用tls
		private String receiver; 			// mail receiver
		private String cc; 					// cc
		private String sender; 				// mail sender
		private String password; 			// mail password
		private String subject; 			// mail subject
		private String message; 			// mail content(can be html)
		private List<String> annexs; 		// mail attachments

		public String getHost() { return this.host; }
		public void setHost(String value) { this.host = value; }

		public int getPort() { return this.port; }
		public void setPort(int value) { this.port = value; }

		public int getConnectTimeout() { return connectTimeout; }
		public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; }

		public int getSendTimeout() { return sendTimeout; }
		public void setSendTimeout(int sendTimeout) { this.sendTimeout = sendTimeout; }

		public boolean getAuth() { return this.auth; }
		public void setAuth(boolean auth) { this.auth = auth; }

		public boolean isDebug() { return debug; }
		public void setDebug(boolean debug) { this.debug = debug; }

		public boolean isTls() { return tls; }
		public void setTls(boolean tls) { this.tls = tls; }

		public String getSender() { return this.sender; }
		public void setSender(String sender) { this.sender = sender; }

		public String getReceiver() { return this.receiver; }
		public void setReceiver(String receiver) { this.receiver = receiver; }

		public String getCC() { return this.cc; }
		public void setCC(String cc) { this.cc = cc; }

		public String getPassword() { return this.password; }
		public void setPassword(String password) { this.password = password; }

		public String getSubject() { return this.subject; }
		public void setSubject(String subject) { this.subject = subject; }

		public String getMessage() { return this.message; }
		public void setMessage(String message) { this.message = message; }

		public List<String> getAnnexs() { return this.annexs; }
		public void setAnnexs(List<String> annexs) { this.annexs = annexs; }
	}

	public static void main(String[] args) {
		MailMsg mail = new MailMsg();
		
		mail.setAuth(true);
		mail.setDebug(true);
		mail.setTls(true);
		mail.setConnectTimeout(0);
		mail.setSendTimeout(0);
		
		mail.setHost("smtp.mosuu.com"); 		//
		mail.setSender("tech@mosuu.com");		//
		mail.setPassword("!M1oa190kB");			//
		mail.setPort(25);
		
		mail.setReceiver("4653664@qq.com");
		mail.setSubject("用户帐号激活通知");
		mail.setMessage("尊敬的会员:\n\n  请点击以下链接进行激活您的帐号！");
		
		MailTool.sendMail(mail);
	}
} 